import  re
import openpyxl
import os
import time
import jieba
import pyautogui
import pyperclip
from wxauto import *
from wxclick import click_picture
word='大小单双，大单，小双，大双'
#outputList = jieba.lcut(inputStr, HMM=False)    #HMM=False 表示只用自己的字典
DEBUG=True

'''
allFeng.xlsx :用来记录客户的全部能量
能量操作.xlsx :用来记录对所来人员的能量增加或减少
recrod.xlsx  :用来记录本局上分或下分的时间

'''

def debug_print(*p):
    if DEBUG:
        print(*p)
def init():
    if not os.path.exists('Data'):
        os.makedirs('Data')
    if not os.path.exists('img'):
        os.makedirs('img')

    file_path = "./img/allFeng.xlsx"
    t = os.path.exists(file_path)
    if not os.path.exists(file_path) :
        wb1=openpyxl.Workbook()
        sheet1=wb1.active
        sheet1['A1'].value = '姓名'
        sheet1['B1'].value = '分数'
        wb1.save('./img/allFeng.xlsx')
        wb1.close()
        wb1.save(file_path)
    if not os.path.exists('./img/today.xlsx'):
        wb2 = openpyxl.Workbook()
        wb2.save('./img/today.xlsx')
    if not os.path.exists('./img/record.xlsx'):
        wb3 = openpyxl.Workbook()
        sheet = wb3.active
        sheet['A1'].value = '姓名'
        sheet['B1'].value = '分数'
        sheet['C1'].value = '时间'
        wb3.save('./img/record.xlsx')
        wb3.close()
    if not os.path.exists("./img/能量操作.xlsx"):
        wb4 = openpyxl.Workbook()
        sheet4 =wb4.active
        sheet4['A1'].value = '姓名'
        sheet4['B1'].value = '上分'
        sheet4['C1'].value = '下分'
        sheet4['D1'].value = '时间'

        #sheet = wb4.active
        wb4.save('./img/能量操作.xlsx')
        wb4.close()



#读出路径下的所有文件
def read_files():
    localPath = './Data/'
    files = []
    for i in os.listdir(localPath):
        #if i == 'allData.xlsx' or i == 'wx_record.xlsx':
            #continue
        files.append(''.join([localPath, i]))
    return files
#新建一个文件
def new_file(name):
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.title = 'sheet1'
    sheet['A1'].value = '姓名：'
    sheet['B1'].value =name
    sheet['A2'].value = '期数'
    sheet['B2'].value = '大'
    sheet['C2'].value = '小'
    sheet['D2'].value = '单'
    sheet['E2'].value = '双'
    sheet['F2'].value = '小单'
    sheet['G2'].value = '小双'
    sheet['H2'].value = '大单'
    sheet['I2'].value = '大双'
    sheet['J2'].value = '结算'
    sheet['K2'].value = '数字'
    curTime = time.localtime()
    #print(str(curTime.tm_mon) + "-" + str(curTime.tm_mday))
    name = './Data/'+name + str(curTime.tm_mon) + "-" + str(curTime.tm_mday) + '.xlsx'
    wb.save(name)

    return wb,sheet
#功能格的转换
def gongNeng_select(gongNeng):
    match gongNeng:
        case '大':
            return 'B'
        case '小':
            return 'C'
        case '单'|'单数':
            return 'D'
        case '双'| '双数':
            return 'E'
        case '小单':
            return 'F'
        case '小双':
            return 'G'
        case '大单':
            return 'H'
        case '大双':
            return 'I'
        case '结算':
            return 'J'
        case '数字':
            return 'K'

#写入数据
def write_data(fileName,times,select,data):

    wb = openpyxl.load_workbook(fileName)
    sheet = wb.active

    for i in range(3,1000):
        qiShu = sheet['A'+str(i)].value
        if qiShu == None:
            sheet['A' + str(i)].value = int(times[0]) + 1
            for j in range(len(data)):
                sheet[gongNeng_select(select[j])+str(i)].value = int(data[j])
            break
    wb.save(fileName)

def guke_name(fileName):
    guKe = re.sub(r'\d+-\d+.xlsx', '', fileName)
    guKe = re.sub('./Data/', '', guKe)
    return guKe
def cancel(fileName):
    allFile = './img/allFeng.xlsx'

    wb = openpyxl.load_workbook(fileName)
    sheet = wb.active
    allWb = openpyxl.load_workbook(allFile)
    allSheet = allWb.active
    cancelFeng =0
    cancelRes=[]

    for i in range(3,1000):
        qiShu = sheet['A'+str(i)].value
        if qiShu == None:
            cancelRes.append(str(sheet['A' + str(i - 1)].value))
            cancelRes.append('\n')
            sheet['A' + str(i - 1)].value = None

            for j in 'BCDEFGHI':
                cancelTmp=sheet[j+str(i-1)].value
                if cancelTmp !=None:
                    cancelFeng +=cancelTmp
                    cancelRes.append(sheet[j + '2'].value)
                    cancelRes.append(str(cancelTmp))
                    sheet[j+str(i-1)].value =None
            break
    wb.save(fileName)

    #总分的取消，在原来的基础上加上去
    debug_print("取消的分数是",cancelFeng)
    guKe=guke_name(fileName)
    for i in range(1,1000):
        guKeTmp =allSheet['A'+str(i)].value
        debug_print("取消时获取的顾客",guKe,guKeTmp)
        if guKeTmp !=None:
            if guKeTmp ==guKe:
                debug_print("终于找到了顾客材料")
                allFengShu =allSheet['B'+str(i)].value
                allFengShu+=cancelFeng
                allSheet['B'+str(i)]=allFengShu
                break
        else:
            break

    debug_print("取消是否跳出来了")
    allWb.save(allFile)
    return cancelFeng,allFengShu,cancelRes

#记录客户上分的时间
def record_FengShu(filename,fengShu):
    '''

    :param filename: 上分的名字
    :param fengShu: 上的分数
    :return:
        A   |   B   |   C
    姓名      分数      时间
    '''
    wb = openpyxl.load_workbook('./img/record.xlsx')
    sheet = wb.active
    for i in range(1,1000):
        name = sheet['A'+str(i)].value
        if name == None:
            sheet['A'+str(i)].value = filename
            sheet['B'+str(i)].value = fengShu
            sheet['C'+str(i)].value = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            break
    wb.save('./img/record.xlsx')
    wb.close()


#总分查找或写入 当输入是True的时候时写入Flasl的时候是查询
def allFeng_find(fileName,cmd,data):
    '''
    :param fileName: 输入的文件名
    :param data:    输入的数据
    cmd :上分，下分，查询,充值，退分
    '''

    allFile = './img/allFeng.xlsx'
    wb = openpyxl.load_workbook(allFile)
    sheet = wb.active
    #提取出顾客
    guKe=guke_name(fileName)


    for i in range(1,1000):
        guKeTmp =sheet['A'+str(i)].value
        if guKeTmp !=None:
            debug_print("allFeng_find里准备的操作命令：",guKeTmp, guKe, cmd)
            if guKe==guKeTmp:
                debug_print("allFeng_find里找到了客户准备操作guKeTmp",i,guKeTmp,guKe, cmd)
                match cmd:
                    case '下分':
                        sheet['B' + str(i)].value -=data
                        resust = sheet['B' + str(i)].value
                    case "上分" | '退分' | '取消':
                        sheet['B' + str(i)].value += data
                        resust = sheet['B' + str(i)].value
                    case '充值':
                        sheet['B' + str(i)].value += data
                        resust = sheet['B' + str(i)].value
                        record_FengShu(guKe,data)
                    case '查询':
                        resust =sheet['B'+str(i)].value
                break
        else:#添加人员信息
            sheet['A'+str(i)].value =guKe
            sheet['B'+str(i)].value =data
            break

    wb.save(allFile)
    wb.close()
    #debug_print("allFeng_find 返回的结果是：",resust)
    return  resust

def send_msg(msg):
    #fous = click_picture('./img/input.png')
    pyperclip.copy(msg)
    pyautogui.hotkey('ctrl', 'v')
    # pyautogui.PAUSE=1
    pyautogui.hotkey('enter')

def today_data(fileName,times,isWrite):
    '''

    :param fileName: 存入文件的名称
    :param isWrite: True 写入 Flase:把today.xlxs里的所有内容去除
    :return:
        A     |      B      |
    Filename    期数（times）
    '''
    wb = openpyxl.load_workbook('./img/today.xlsx')
    sheet = wb.active

    if isWrite:#        写入数据
        debug_print("today_data 准备写入数据 isWrite=True")
        for i in range(1,1000):
            name = sheet['A' + str(i)].value
            if name != None:
                if name == fileName:
                    sheet['B' + str(i)].value = int(times[0])+1
                    break
            else:
                sheet['A' + str(i)].value = fileName
                sheet['B' + str(i)].value = int(times[0])+1
                break
    else:#把today.xlxs里的所有内容去除
        debug_print("today_data 擦除数据 isWrite=Flase")
        for i in range(1,1000):
            name = sheet['A' + str(i)].value
            if name != None:
                sheet['A'+ str(i)].value =None
                sheet['B'+ str(i)].value =None
            else:
                break
    wb.save('./img/today.xlsx')
    wb.close()

#输入的数据处理
def input_data(inputStr,times,fileName,cmd):
    '''
    :param inputStr: 输入字符串
    :param times:
    :param fileName:
    :param cmd: 上分，下分，查询，取消
    :return:
    '''

    debug_print("进入input_data，要操作的客户是：",fileName)
    outputList = jieba.lcut(inputStr, HMM=False)    #HMM=False 表示只用自己的字典
    debug_print("input_data 输入的内容是和拆散字词",inputStr,outputList,times)
    #准备数据的写入文档
    #判断关键字的个数与输入的数字一不一样，如果一样说明输入正确
    data = re.findall(r'\d+', inputStr)
    caoZuo = re.findall(r'[\u4e00-\u9fa5]+', inputStr)

    debug_print("总计此次的分数")
    #计算要下的总分数
    #顾客要上分时，先查询现在有多少分，如果分数不足，不可以上分
    allFengShu=0
    for i in data:  #计算这次使用的总分数
        allFengShu+=int(i)
    if caoZuo[0] =='上分':    #上分操作
        debug_print("单独的上分操作")
        result =allFeng_find(fileName,'上分',allFengShu)  #进行写入操作
        wxPrint=guke_name(fileName)+":"+"您现本次上的分是："+str(allFengShu)+'\n'+"您上分后的总分数是："+str(result)
        send_msg(wxPrint)
        debug_print("您上分后现在的总分数是",result)


        return
    if caoZuo[0] =='查询':#查询操作
        debug_print("单独的查询操作")
        result =allFeng_find(fileName,'查询',data)  #进行写入操作
        debug_print("查到您的总分数是",result)
        guke=guke_name(fileName)
        wxPrint=guke+':'+"你的总数是："+str(result)
        send_msg(wxPrint)
        return
    if caoZuo[0] =='取消':#查询操作
        debug_print("单独的取消操作")
        fengShu,resust,cancelRes= cancel(fileName)
        debug_print("您分数和剩余的分数是", fengShu,resust,cancelRes,''.join(cancelRes))
        wxPrint=guke_name(fileName)+":"+"取消的单是："+''.join(cancelRes)+'\n'+"您剩余的分数是："+str(resust)
        send_msg(wxPrint)
        return
    if len(data) != len(caoZuo):
        debug_print("您输入的数字有误，请重新再输入")
        return
    result = allFeng_find(fileName, '查询', data)
    debug_print("查询出来的总分是：",result)
    if result ==None:
        return
    debug_print("准备操作的命令是：",cmd)
    match cmd:
        case '下分':
            debug_print("准备为您上分")
            if result<allFengShu:
                debug_print("很抱款您的分数不足")
            else:
                result =allFeng_find(fileName, '下分', allFengShu)
                write_data(fileName, times, caoZuo, data)
                debug_print("这次使用的攻击能量是：",caoZuo,data)
                curTime=time.localtime()
                debug_print("您的下注成功,剩余分数：",result)
                today_data(fileName, times, True)
                tmp=[]
                for i in range(len(caoZuo)):
                    tmp.append("/:heart /:heart")
                    tmp.append(caoZuo[i])
                    tmp.append(data[i])
                    tmp.append("\n")
                tmp =''.join(tmp)
                wxPrint=(guke_name(fileName)+"/:rose /:rose"+"\n"+
                         "编号："+str(int(times[0])+1)+"\n"+
                         str(curTime.tm_year)+"-"+str(curTime.tm_mon)+"-"+str(curTime.tm_mday)+"  "+str(curTime.tm_hour)+":"+str(curTime.tm_min)+":"+str(curTime.tm_sec)+"\n"+
                         tmp+#"/:heart /:heart"+"\n"+
                         "攻击能量：-"+str(allFengShu)+'\n'+"胜鱼的能量："+str(result))
                send_msg(wxPrint)
        case '下分':
            if result<data:
                debug_print("您的分数不足")
            else:
                allFeng_find(fileName, '下分', allFengShu)
        case '查询':
            result = allFeng_find(fileName, '查询', data)
            debug_print("您的查询到的分数是",result)
            wxPrint = guke_name(fileName) + ":" + "为您查询到的分数是：" + str(result)
            send_msg(wxPrint)
        case '取消':
            debug_print("准备取消上的分数")
            fengShu = cancel(fileName)
            allFeng_find(fileName, '取消', fengShu)
            debug_print("您剩余的分数是", fengShu)


#将结果发到微信
def send_to_wx(fileName,times,res,data,curTime):
    #删除Data和。xlsx
    getRes=[]
    name =re.sub('./Data/','',fileName)
    name =re.sub('.xlsx','',name)
    for i in range(3,1000):
        qiShu = fileName['A'+str(i)].value
        if qiShu == times:
            for j in 'BCDEFGHI':#将这I行的所有分数相加
                fenShu=fileName[j+str(i)].value
                if fenShu !=None:
                    getRes.append(fenShu)
            debug_print("得到的结果是",getRes)
            jieSuna(fileName,times,res,data)
            #

            break
def get_fengShu(value,showfenShu,getfenShu):
    tmp =[]

    if getfenShu>0:
        tmp.append('/:sun') #阳光表情
        tmp.append(value)
        tmp.append(str(showfenShu))
        tmp.append(">>+")
    else:
        tmp.append("/::~")#撇嘴
        tmp.append(value)
        tmp.append(str(showfenShu))
        tmp.append(">>")
    tmp.append(str(getfenShu))
    tmp.append('\n')
    return tmp


def beilv(key,value):
    if value == 0:
        return  0, 0
    if value < 0:
        return -value,value

    match key:
        case '大' | '小' | '单' | '双':
            if value != 0:
                return  value / 2, value
        case '大单' | '小双':
            return value / 3, value
        case '小单' | '大双':
            return value / 3.5, value
def jieSuna(oldTime,res,data,curTime):
    allFengShu =0
    uersFengShu =0
    zhongFengShu =0
    getRes =[]
    allRes =[]
    doName =[]
    debug_print("进入结算")

    #从today.xlsx中读出当期使用的人
    todayWb = openpyxl.load_workbook('./img/today.xlsx')
    todaySheet = todayWb.active
    for i in range(1,1000):
        name = todaySheet['A'+str(i)].value
        if name !=None:
            doName.append(name)
        else:
            break

    debug_print("当使用的人是：",doName)
    todayWb.close()
    for fileName in doName:
        wb = openpyxl.load_workbook(fileName)
        sheet = wb.active

        resuslt_dict = {'大': 0, '小': 0, '单': 0, '双': 0, '大单': 0, '小单': 0, '大双': 0, '小双': 0}
        '''倍率           2       2         2        2         3          3.5       3.5       3 '''
        tmp=[]
        tmp.append("编号：")  # 花 编号：9527 结果
        tmp.append(oldTime[0])  # 期数
        tmp.append("结果/:rose")
        tmp.append('\n')

        tmp.append(oldTime[2])  # 1+2+3=6 小双
        tmp.append("   ")
        tmp.append(res[2])
        tmp.append('\n')

        # tmp.append(guke_name(doName))
        tm1 = str(curTime.tm_year) + "-" + str(curTime.tm_mon) + "-" + str(curTime.tm_mday) + "  " + str(
            curTime.tm_hour) + ":" + str(curTime.tm_min) + ":" + str(curTime.tm_sec)
        tmp.append("【自动】")  # 【自动】 1：2：3
        tmp.append(tm1)
        tmp.append('\n')

        for i in range(3,1000):

            qiShu =sheet['A'+str(i)].value
            if qiShu !=None:#对下单基数的读取

                debug_print("读出的期数是：",qiShu,"老的期数是：",oldTime[0])

                if qiShu == int(oldTime[0]):
                    debug_print("找到相同的期")
                    debug_print("中奖结果", res)



                    guKe=guke_name(fileName)#name 花花
                    '''tmp.append(guKe)
                    tmp.append('/:rose/:rose')
                    tmp.append('.\n')'''



                    allFengShu =0
                    zhongFengShu = 0
                    theTimeGet=0
                    theTimeloss=0
                    for k in 'BCDEFGHI':#将这I行的所有分数相加
                         fenShu=sheet[k+str(i)].value
                         if fenShu !=None:
                             value=sheet[k+'2'].value   #获取的值大、小、大双等值
                             allFengShu += fenShu#这里准备计算分值了，赔率

                             if value ==res[0] or value ==res[1] or value ==res[2]: #进这里面表示中的
                                 match value:
                                     case '双'|'单'|'大'|'小':
                                            zhongFengShu += fenShu*2
                                            debug_print("value值：", value, fenShu, ">>+", fenShu*2)
                                            #tmp.extend(get_fengShu(value, fenShu, fenShu*2))
                                            #theTimeGet +=fenShu*2
                                            resuslt_dict[value] +=fenShu*2
                                            #debug_print(tmp)
                                     case   '大双'|'小单':
                                            zhongFengShu += fenShu*3.5
                                            debug_print("value值：", value, fenShu, ">>+", fenShu*3.5)
                                            #tmp.extend(get_fengShu(value, fenShu, fenShu * 3.5))
                                            #theTimeGet += fenShu * 3.5
                                            resuslt_dict[value] += fenShu *3.5
                                            #debug_print(tmp)
                                     case  '大单'|'小双':
                                            zhongFengShu += fenShu * 3
                                            debug_print("value值：", value, fenShu, ">>+", fenShu * 3)
                                            #tmp.extend(get_fengShu(value, fenShu, fenShu * 3))
                                            #theTimeGet += fenShu * 3
                                            resuslt_dict[value] += fenShu *3
                                            #debug_print(tmp)
                             else:
                                resuslt_dict[value] +=-fenShu
                                debug_print(value,'>>','[',fenShu,']')
                                #tmp.extend(get_fengShu(value, fenShu, -fenShu))
                                theTimeloss +=-fenShu

                             #debug_print("value值：", value, fenShu, ">>+", fenShu)

                    #对本局分数的总结


                    debug_print("上的分数是",allFengShu)
                    debug_print(tmp)
                    sheet['J'+str(i)].value=allFengShu  #将分数写入
                    sheet['K'+str(i)].value=data    #中奖数字写入

                    uersFengShu +=allFengShu

                    debug_print("本期使用的分数",uersFengShu)
            else:
                for i in range(3,1000):
                    qiShu =sheet['A'+str(i)].value
                    if qiShu !=None:
                        if qiShu == int(oldTime[0]):
                            fenShu =sheet['J'+str(i)].value
                            if fenShu <1:   #当分数小于1时，说明有中奖的
                                for j in range(3):#每次返回的只有三个结果
                                    resTmp = sheet[gongNeng_select(res[j]) + str(i)].value#根据中奖来读
                                    if resTmp != None:
                                        debug_print("中的奖是：",resTmp,res[j])
                    else:
                        break
                break
        wb.save(fileName)
        keys = resuslt_dict.keys()
        allFengShu = 0
        uersFengShu =0
        for value in keys:
            xia, jin = beilv(value, resuslt_dict[value])
            if xia != 0:
                uersFengShu +=jin if jin>0 else 0
                allFengShu+=jin
                debug_print("本次进的结果是：",allFengShu,jin,uersFengShu)
                tmp.extend(get_fengShu(value, xia, jin))
        if uersFengShu > 0:  # 说明有分数进
            debug_print("这次是有收入的")
            result = allFeng_find(fileName, '上分', uersFengShu)
            tmpStr = '/:sun' + '收获能量:' + str(allFengShu) + '\n'
            tmp.append(tmpStr)
            tmpStr = "/:circle" + '您的能量是：' + str(result)
            tmp.append(tmpStr)
        else:
            debug_print("巴比Q")
            result = allFeng_find(fileName, '查询', theTimeGet)
            tmpStr = '/:sun' + '收获能量:' + str(allFengShu) + '\n'
            tmp.append(tmpStr)
            tmpStr = "/:circle" + '您的能量是：' + str(result)
            tmp.append(tmpStr)
        debug_print("result_dict的结果是：", resuslt_dict)
        wx = WeChat()
        wx.Search(guKe)
        send_msg(''.join(tmp))


    today_data("chachu", oldTime[0], False)#用来除的
    debug_print("本期使用的分数:",uersFengShu)



